# -*- encoding=utf8 -*-

__author__ = "code哥"
import subprocess
import json
import os
from sanic.blueprints import Blueprint
from sanic.views import HTTPMethodView
from sanic import response
from sanic_openapi import doc
from conf.app_conf import GlobalMap

# 记录port累加值
global_var_index = 48000

blueprint = Blueprint(__name__, '/api')


class RegWifiDevices(HTTPMethodView):

    @doc.summary("注册WiFi设备")
    def get(self, request):
        args = request.get_args(keep_blank_values=True)
        # {'client': ['10.0.0.8'], 'serial': ['e9bd483']}
        client = args.get('client', '')
        serial = args.get('serial', '')
        if len(client) <= 0 and len(serial) <= 0:
            return response.json({'code': 500, 'data': 'fail'})
        # 注册设备，记录ip 设备 端口
        global global_var_index
        global_var_index = global_var_index + 1
        port = global_var_index
        res = adb_shell('-s %s tcpip %s' % (serial, port,))
        print('adb wifi res ==>> ' + res)
        if str(port) in res:
            GlobalMap().set_value('rym_' + str(serial), dict(port=str(port), client=str(client)))
            # 写入文件
            write_file(GlobalMap().get_global_dic())
            return response.json({'code': 0, 'data': 'success'})
        else:
            return response.json({'code': 500, 'data': 'fail'})


blueprint.add_route(RegWifiDevices.as_view(), '/reg_wifi_devices', strict_slashes=True)


def write_file(dic):
    with open('{path}/conf/devices_list_wifi.conf'.format(path=
                                                          os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
              'w') as f:
        f.write(json.dumps(dic))
        f.close()


def adb_shell(command):
    adb_path_command = """
        mdfind -name "platform-tools" | grep "Android/sdk/platform-tools" | awk '{print $1}'
    """
    adb_path_process = subprocess.Popen(
        adb_path_command,
        shell=True, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    adb_path_process.wait()
    adb_path = adb_path_process.stdout.read().decode('utf-8')
    devices_command = """
        %s/adb %s
    """ % (
        adb_path.replace('\r', '').replace('\n', '').replace('\r\n', ''), command,)
    shell_process = subprocess.Popen(
        devices_command,
        shell=True, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    shell_process.wait()
    return shell_process.stdout.read().decode('utf-8')
